package me.panpf.sketch;

import me.panpf.sketch.drawable.DrawableCallback;
import me.panpf.sketch.util.Log;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.element.Element;
import ohos.agp.render.BlendMode;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.agp.utils.Matrix;
import ohos.app.Context;
import ohos.media.image.ImageSource;

import java.util.ArrayList;
import java.util.List;

public class DrawableImage extends Image implements DrawableCallback, Component.DrawTask {
    Matrix matrix;


    public DrawableImage(Context context) {
        this(context, null);
    }

    public DrawableImage(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public DrawableImage(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        super.addDrawTask(this);
    }

    @Override
    public void invalidateDrawable(Element who) {
        invalidate();
    }

    @Override
    public void invalidate() {
        super.invalidate();
    }

    public void setMatrix(Matrix matrix) {
        this.matrix = matrix;
        invalidate();
    }

    @Override
    public void scheduleDrawable(Element who, Runnable what, long when) {

    }

    @Override
    public void unscheduleDrawable(Element who, Runnable what) {

    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        final Element element = getImageElement();
        if (element == null) {
            return;
        }


        final int saveCount = canvas.getSaveCount();
        canvas.save();


        if (matrix != null) {
            canvas.concat(matrix);
            element.drawToCanvas(canvas);
            canvas.restoreToCount(saveCount);
            setPixelMap(null);
        } else {
            if (element instanceof PixelMapDrawable) {
                element.drawToCanvas(canvas);
            }
        }

    }
}
